import { fetchEventSource,EventStreamContentType } from "@microsoft/fetch-event-source";


// 处理get请求
export function sseRequestGet(url: string, successCallback: Function, closeCallback?: Function, errCallback?: Function){
    return sseRequest(url,'GET', undefined, successCallback, closeCallback, errCallback)
}

// 处理post请求
export function sseRequestPost(url: string,data:object|undefined, successCallback: Function, closeCallback?: Function, errCallback?: Function){
  return sseRequest(url,'POST',data,successCallback, closeCallback, errCallback)
}

// 流式传输处理函数
export function sseRequest(url: string,method:String, data: object|undefined, successCallback: Function, closeCallback?: Function, errCallback?: Function) {
  const abortController = new AbortController()

  const req:any={
    method: method,
    headers: {
      'Content-Type': 'application/json;charset=utf-8',
      'Accept': '*/*',
      'token': localStorage.getItem('token')!
    },
    body: data?JSON.stringify(data):data,
    openWhenHidden: true, // 取消visibilityChange事件
    signal: abortController.signal, // AbortSignal
    // 按需添加此函数，不用就不添加
    async onopen(response) {
        if (response.ok && response.headers.get('content-type') === EventStreamContentType) {
            return; // everything's good
        } else if (response.status >= 400 && response.status < 500 && response.status !== 429) {
            // client-side errors are usually non-retriable:
            // throw new FatalError();
            throw new Error();
        } else {
            // throw new RetriableError();
            throw new Error();
        }
    },
    onmessage(ev) {
      // 每当消息推送过来时，就调用处理函数处理消息
      successCallback(ev)
    },
    onerror(err) {
      abortController.abort()
      if (errCallback) { errCallback(err) }
      throw err
    },
    onclose() {
      abortController.abort()
      if (closeCallback) { closeCallback() }
    }
  }

  // 此处用baseApi
  if(!url.startsWith('http')){
    url=import.meta.env.VITE_APP_BASE_API + url;
  }
  fetchEventSource(url, req)
}

// 调用sseRequest示例：
// export const beginWrite = (topic: string, styleId: string, style: string) => {
//   const writeStore = useWriteStore()
//   function successCallback(ev: { data: string, event: string, id: string, retry: number }) {
//     if (ev.event === 'message') {
//       const newStr = ev.data.replace(/_::_/g, '\n\n').replace(/_:_/g, '\n').replace(/_._/g, ' ')
//       writeStore.sseInput += newStr
//     }
//     if (ev.event === 'message_end') {
//       writeStore.sseInput = ''
//     }
//   }
//   sseRequest('/knowledge/know_write', { topic, styleId, style }, successCallback)
// }
